<?php

namespace app\model;

use think\model\concern\SoftDelete;

/**
 * Description of Dynamic
 *
 * @author suiyuan
 */
class Dynamic extends \think\Model 
{
    use SoftDelete;
    protected $deleteTime = 'delete_at';
    protected $defaultSoftDelete = null;

    protected $table = 'dynamic';

    protected $field = ['user_id', 'status', 'title', 'dist_id', 'delete_at'];

    /*
     * 新增前
     */
    public static function onBeforeInsert($model)
    {
        $model->user_id = request()->uid;
    }   
    public static function onAfterWrite ($model) {
        // 非综合题题干,增加答案选项
        if(request()->has('album')) {
            $data = $model->getData('album');
            $existIds = [];
            foreach($data as $k => $row){
                $data[$k]['dynamic_id'] = $model->id;
                isset($row['id']) && ($existIds[] = $row['id']);
            }

            if(!$model->isEmpty()){
                $ids = DynamicAlbum::where('dynamic_id', $model->id)->whereNotIn('id', $existIds)->column('id');
                // $data = array_merge($data, array_map(fn($v) => ['id' => $v, 'delete_at' => time()], $ids));
                foreach($ids as $id){
                    $data[] = ['id' => $id, 'delete_at' => time()];
                }
            }
            $album = new DynamicAlbum;
            $album->saveAll($data);
        }
    }
    protected function setTitleAttr($value)
    {
        return trim($value, "\t\n\r\s");
    }
    /**
     * 用户搜索
     *
     * @param [type] $query
     * @param [type] $value
     * @param [type] $data
     * @return void
     */
    public function searchUserIdAttr($query, $value, $data)
    {
        $value > 0 && $query->where('user_id', $value);
    }
    /**
     * 题目搜索
     *
     * @param [type] $query
     * @param [type] $value
     * @param [type] $data
     * @return void
     */
    public function searchTitleAttr($query, $value, $data)
    {
        !empty($value) && $query->where('title', 'like', '%' . $value . '%');
    }
    /**
     * 状态搜索
     *
     * @param [type] $query
     * @param [type] $value
     * @param [type] $data
     * @return void
     */
    public function searchStatusAttr($query, $value, $data)
    {
        $value > 0 && $query->where('status', $value);
    }
    /**
     * 用户
     *
     * @return void
     */
    public function user() {
        return $this->belongsTo('User')->bind(['nickname']);
    }
    /**
     * 答案
     *
     * @return void
     */
    public function album() {
        return $this->hasMany('DynamicAlbum','dynamic_id')->where('delete_at', '=', 0);
    }
    /**
     * 相册
     *
     * @return void
     */
    public function comments() {
        return $this->hasMany('DynamicComment','dynamic_id')->where('delete_at', '=', 0);
    }
}
